package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.common.Result;
import com.example.entity.Account;
import com.example.entity.User;
import com.example.exception.CustomException;
import com.example.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户业务处理
 **/
@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 登录
     */
    public Account login(Account account) {
        Account user = userMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(user)) {
            throw new CustomException("该账号不存在，请先注册");
        }
        if (!account.getPassword().equals(user.getPassword())) {
            throw new CustomException("账号或密码错误");
        }
        return user;
    }

    /**
     * 分页查询
     * @param user
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo selectPage(User user, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userMapper.selectAll(user);
        return PageInfo.of(list);
    }

    /**
     * 查询用户观影列表
     * @param id
     * @return
     */
    public User selectUser(Integer id) {
        return userMapper.selectById(id);
    }

    /**
     * 新增
     * @param user
     */
    public void add(User user){
        User newUser = userMapper.selectByUsername(user.getUsername());
        if (ObjectUtil.isNotNull(newUser)) {
            throw new CustomException("该账号已存在，请前往登录");
        }
        //未设置昵称，默认为用户名
        if (ObjectUtil.isEmpty(user.getName())) {
            user.setName(user.getUsername());
        }
        user.setRole("USER");
        userMapper.add(user);
    }

    /**
     * 修改用户
     * @param user
     */
    public void updateById(User user) {
        User selectUser = userMapper.selectById(user.getId());
        if(user.getNewPassword() != null){
            user.setPassword(user.getNewPassword());
        }
        if(selectUser.getName().equals(user.getName()) && selectUser.getAvatar().equals(user.getAvatar()) && user.getNewPassword() == null){
            throw new CustomException("用户资料未修改");
        }
        userMapper.updateById(user);
    }

    /**
     * 删除
     * @param id
     */
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param ids
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            userMapper.deleteById(id);
        }
    }
}